package com.lowcode.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lowcode.platform.common.PageResult;
import com.lowcode.platform.common.Result;
import com.lowcode.platform.dto.LoginRequest;
import com.lowcode.platform.dto.LoginResponse;
import com.lowcode.platform.entity.User;
import com.lowcode.platform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        LoginResponse response = userService.login(request);
        return Result.success(response);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Void> register(@RequestBody User user) {
        userService.register(user);
        return Result.success();
    }

    /**
     * 分页查询用户
     */
    @GetMapping("/page")
    public Result<PageResult<User>> page(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer status) {
        
        Page<User> page = new Page<>(current, size);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(username)) {
            wrapper.like(User::getUsername, username);
        }
        if (status != null) {
            wrapper.eq(User::getStatus, status);
        }
        
        IPage<User> result = userService.page(page, wrapper);
        
        PageResult<User> pageResult = new PageResult<>(
                result.getTotal(),
                result.getRecords(),
                result.getCurrent(),
                result.getSize()
        );
        
        return Result.success(pageResult);
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable Long id) {
        User user = userService.getById(id);
        // 隐藏密码
        user.setPassword(null);
        return Result.success(user);
    }

    /**
     * 新增用户
     */
    @PostMapping
    public Result<Void> add(@RequestBody User user) {
        userService.register(user);
        return Result.success();
    }

    /**
     * 更新用户
     */
    @PutMapping
    public Result<Void> update(@RequestBody User user) {
        // 不允许修改密码
        user.setPassword(null);
        userService.updateById(user);
        return Result.success();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        userService.removeById(id);
        return Result.success();
    }

    /**
     * 为用户分配角色
     */
    @PostMapping("/{userId}/roles")
    public Result<Void> assignRoles(
            @PathVariable Long userId,
            @RequestBody List<Long> roleIds) {
        
        userService.assignRoles(userId, roleIds);
        return Result.success();
    }

    /**
     * 获取用户的角色ID列表
     */
    @GetMapping("/{userId}/roles")
    public Result<List<Long>> getUserRoleIds(@PathVariable Long userId) {
        List<Long> roleIds = userService.getUserRoleIds(userId);
        return Result.success(roleIds);
    }

    /**
     * 验证用户身份（找回密码第一步）
     */
    @PostMapping("/verify-identity")
    public Result<Void> verifyIdentity(@RequestBody User user) {
        if (user.getUsername() == null || user.getNickname() == null) {
            return Result.error("用户名和昵称不能为空");
        }
        userService.verifyIdentity(user.getUsername(), user.getNickname());
        return Result.success();
    }

    /**
     * 重置密码（需要用户名、昵称和新密码）
     */
    @PostMapping("/reset-password")
    public Result<Void> resetPassword(@RequestBody User user) {
        if (user.getUsername() == null || user.getNickname() == null || user.getPassword() == null) {
            return Result.error("用户名、昵称和密码不能为空");
        }
        userService.resetPassword(user.getUsername(), user.getNickname(), user.getPassword());
        return Result.success();
    }

}
